/*
 * Copyright (C) 2018 Logos Technology Ltd.
 */

package com.logos.common.source.network.interceptor;

import com.logos.tool.string.StringUtil;

import java.io.EOFException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

import okhttp3.Connection;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.http.HttpHeaders;
import okhttp3.internal.platform.Platform;
import okio.Buffer;
import okio.BufferedSource;
import okio.GzipSource;

import static okhttp3.internal.platform.Platform.INFO;

public final class LoggerInterceptor implements Interceptor {
    private static final Charset UTF8 = Charset.forName("UTF-8");

    public enum Level {
        NONE,
        BASIC,
        HEADERS,
        BODY
    }

    /**
     * Logger
     */
    public interface Logger {
        /**
         * log
         *
         * @param message message
         */
        void log(String message);

        /**
         * A {@link Logger} defaults output appropriate for the current platform.
         */
        Logger DEFAULT = new Logger() {
            @Override
            public void log(String message) {
                Platform.get().log(INFO, message, null);
            }
        };
    }

    public LoggerInterceptor() {
        this(Logger.DEFAULT);
    }

    public LoggerInterceptor(Logger logger) {
        this.mLogger = logger;
    }

    private final Logger mLogger;

    private volatile Level mLevel = Level.NONE;

    /**
     * Change the level at which this interceptor logs.
     *
     * @param level level
     * @return level
     */
    public LoggerInterceptor setLevel(Level level) {
        if (level == null) {
            throw new NullPointerException("level == null. Use Level.NONE instead.");
        }
        this.mLevel = level;
        return this;
    }

    public Level getLevel() {
        return mLevel;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Level level = this.mLevel;

        Request request = chain.request();
        if (level == Level.NONE) {
            return chain.proceed(request);
        }

        boolean logBody = level == Level.BODY;
        boolean logHeaders = logBody || level == Level.HEADERS;

        RequestBody requestBody = request.body();
        boolean hasRequestBody = requestBody != null;

        Connection connection = chain.connection();
        String requestStartMessage = "--> "
                + request.method()
                + ' ' + request.url()
                + (connection != null ? " " + connection.protocol() : "");
        if (!logHeaders && hasRequestBody) {
            requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
        }
        mLogger.log(requestStartMessage);

        if (logHeaders) {
            if (hasRequestBody) {
                // Request body headers are only present when installed as a network interceptor.
                // Force them to be included (when available) so there values are known.
                if (requestBody.contentType() != null) {
                    mLogger.log("Content-Type: " + requestBody.contentType());
                }
                if (requestBody.contentLength() != -1) {
                    mLogger.log("Content-Length: " + requestBody.contentLength());
                }
            }

            Headers headers = request.headers();
            for (int i = 0, count = headers.size(); i < count; i++) {
                String name = headers.name(i);
                // Skip headers from the request body as they are explicitly logged above.
                if (!"Content-Type".equalsIgnoreCase(name)
                        && !"Content-Length".equalsIgnoreCase(name)) {
                    mLogger.log(name + ": " + headers.value(i));
                }
            }

            if (!logBody || !hasRequestBody) {
                mLogger.log("--> END " + request.method());
            } else if (bodyHasUnknownEncoding(request.headers())) {
                mLogger.log("--> END " + request.method() + " (encoded body omitted)");
            } else {
                Buffer buffer = new Buffer();
                requestBody.writeTo(buffer);

                Charset charset = UTF8;
                MediaType contentType = requestBody.contentType();

                String subtype = null;

                if (contentType != null) {
                    subtype = contentType.subtype();
                }

                if (contentType != null) {
                    charset = contentType.charset(UTF8);
                }

                mLogger.log("");
                if (isPlaintext(buffer)) {
                    String readString = buffer.readString(charset);
                    if (isNotFileRequest(subtype)) {
                        mLogger.log(readString);
                    } else {
                        String boundary = null;
                        if (contentType != null) {
                            String typeString = contentType.toString();
                            String[] types = typeString.split(";");
                            for (String string : types) {
                                if (string.contains("boundary")) {
                                    boundary = string.split("=")[1];
                                }
                            }
                        } else {
                            String[] split = readString.split("\n");
                            if (split.length > 0) {
                                boundary = split[0];
                            }
                        }

                        if (boundary != null) {
                            String[] strings = readString.split("--" + boundary);
                            for (String bodyString : strings) {
                                String[] oneBody = bodyString.split("\n");
                                if (oneBody.length >= 5) {
                                    mLogger.log("{ \n");
                                    for (int i = 0; i < 5; i++) {
                                        if (!StringUtil.isEmpty(oneBody[i])) {
                                            mLogger.log("   " + oneBody[i]);
                                        }
                                    }
                                    mLogger.log("} \n");
                                }
                            }
                        }
                    }
                    mLogger.log("--> END " + request.method()
                            + " (" + requestBody.contentLength() + "-byte body)");
                } else {
                    mLogger.log("--> END " + request.method() + " (binary "
                            + requestBody.contentLength() + "-byte body omitted)");
                }
            }
        }

        long startNs = System.nanoTime();
        Response response;
        try {
            response = chain.proceed(request);
        } catch (Exception e) {
            mLogger.log("<-- HTTP FAILED: " + e);
            throw e;
        }
        long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

        ResponseBody responseBody = response.body();
        long contentLength = responseBody.contentLength();
        String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
        mLogger.log("<-- "
                + response.code()
                + (response.message().isEmpty() ? "" : ' ' + response.message())
                + ' ' + response.request().url()
                + " (" + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ')');

        if (logHeaders) {
            Headers headers = response.headers();
            for (int i = 0, count = headers.size(); i < count; i++) {
                mLogger.log(headers.name(i) + ": " + headers.value(i));
            }

            if (!logBody || !HttpHeaders.hasBody(response)) {
                mLogger.log("<-- END HTTP");
            } else if (bodyHasUnknownEncoding(response.headers())) {
                mLogger.log("<-- END HTTP (encoded body omitted)");
            } else {
                BufferedSource source = responseBody.source();
                source.request(Long.MAX_VALUE); // Buffer the entire body.
                Buffer buffer = source.buffer();
                //TODO 当加密之后解析buffer就可以了
                Long gzippedLength = null;
                if ("gzip".equalsIgnoreCase(headers.get("Content-Encoding"))) {
                    gzippedLength = buffer.size();
                    GzipSource gzippedResponseBody = null;
                    try {
                        gzippedResponseBody = new GzipSource(buffer.clone());
                        buffer = new Buffer();
                        buffer.writeAll(gzippedResponseBody);
                    } finally {
                        if (gzippedResponseBody != null) {
                            gzippedResponseBody.close();
                        }
                    }
                }

                Charset charset = UTF8;
                MediaType contentType = responseBody.contentType();
                if (contentType != null) {
                    charset = contentType.charset(UTF8);
                }

                if (!isPlaintext(buffer)) {
                    mLogger.log("");
                    mLogger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
                    return response;
                }

                if (contentLength != 0) {
                    mLogger.log("");
                    mLogger.log(buffer.clone().readString(charset));
                }

                if (gzippedLength != null) {
                    mLogger.log("<-- END HTTP (" + buffer.size() + "-byte, "
                            + gzippedLength + "-gzipped-byte body)");
                } else {
                    mLogger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
                }
            }
        }

        return response;
    }

    /**
     * Returns true if the body in question probably contains human readable text.
     * Uses a small sample of code points to detect unicode control characters commonly
     * used in binary file signatures.
     */
    static boolean isPlaintext(Buffer buffer) {
        try {
            Buffer prefix = new Buffer();
            long byteCount = buffer.size() < 64 ? buffer.size() : 64;
            buffer.copyTo(prefix, 0, byteCount);
            for (int i = 0; i < 16; i++) {
                if (prefix.exhausted()) {
                    break;
                }
                int codePoint = prefix.readUtf8CodePoint();
                if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
                    return false;
                }
            }
            return true;
        } catch (EOFException e) {
            return false; // Truncated UTF-8 sequence.
        }
    }

    private boolean bodyHasUnknownEncoding(Headers headers) {
        String contentEncoding = headers.get("Content-Encoding");
        return contentEncoding != null
                && !contentEncoding.equalsIgnoreCase("identity")
                && !contentEncoding.equalsIgnoreCase("gzip");
    }

    private boolean isNotFileRequest(final String subtype) {
        return subtype != null && (subtype.contains("json")
                || subtype.contains("xml")
                || subtype.contains("plain")
                || subtype.contains("html"));
    }
}
